package cn.fbs.service;

import cn.fbs.dao.dm.*;
import cn.fbs.enums.ExamineEnum;
import cn.fbs.enums.MediaEnum;
import cn.fbs.model.NewTCodeTargetType;
import cn.fbs.model.TImageInfo;
import cn.fbs.model.TVideoInfo;
import cn.fbs.model.dm.*;
import cn.fbs.util.AESUtils;
import cn.fbs.vo.GroupAndTarget;
import cn.fbs.vo.SysGroupVo;
import cn.fbs.vo.UpdateUserInfoVo;
import cn.fbs.vo.SysUserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author yuyuesheng
 * @version 1.0
 * @description: TODO
 * @date 2021/4/1 10:45
 */
@Service
public class UserInfoService {

    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysGroupMapper groupMapper;

    @Autowired
    private GroupTargetMapper groupTargetMapper;
    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private DMNewTargetMapper targetMapper;

    @Autowired
    private DMImageInfoMapper imageInfoMapper;

    @Autowired
    private DMVideoInfoMapper videoInfoMapper;

    @Autowired
    private UserExamineMapper examineMapper;

    @Autowired
    private UserTargetMapper userTargetMapper;
    private static final String IV_STRING = "F431E6FF9051DA07";

    public Object regist(SysUserVo vo) {
        if (vo.getUserId() == null || vo.getUserId() == 0) {
            String loginName = vo.getLoginName();
            //检查用户名是否唯一
            boolean userExisted = checkUsernameUnique(loginName);
            if (userExisted) {
                return "500,用户已存在";
            }
            //设置用户名密码
            String passWord = vo.getPassword();
            if (StringUtils.isBlank(loginName)) {
                return "500,登录名不可为空";
            }
            if (StringUtils.isBlank(passWord)) {
                return "500,密码不可为空";
            }
            String DPassWord = AESUtils.encryptData(IV_STRING, passWord);
            vo.setPassword(DPassWord);
            if (StringUtils.isBlank(vo.getUserName())) {
                vo.setUserName("游客");
            }
            if (StringUtils.isBlank(vo.getUserRole())) {
                vo.setUserRole("2");
            }
            vo.setCreateTime(new Date());
            userMapper.insertSelective(vo);

            if ("1".equals(vo.getUserRole())|| "2".equals(vo.getUserRole()))
            {
                return "200,注册成功";
            }
                UserGroup userGroup = new UserGroup();
                userGroup.setGroupId(vo.getGroupId());
                userGroup.setRoleType(vo.getRoleType());
                userGroup.setUserId(vo.getUserId());
            if (vo.getRoleType().equals("3")) {
                userGroup.setGroupId((long) 0);
            }
            userGroupMapper.insertSelective(userGroup);

            return "200,注册成功";
        } else {
            return this.updateUser(vo);
        }
    }

    //判断用户名是否唯一
    public boolean checkUsernameUnique(String loginName) {
        Integer count = userMapper.selectCount(loginName);

        if (count > 0) {
            return true;
        }
        return false;
    }

    public String updateUserInfo(UpdateUserInfoVo updateUserInfoVo) {
        Long id = updateUserInfoVo.getId();
        //根据用户主键查找用户信息
        SysUser sysUser = userMapper.selectByPrimaryKey(id);

        if (sysUser != null) {
            String password = sysUser.getPassword();
            //获取解码后的密码
            String dataPass = AESUtils.decryptData(password);

            if (dataPass.equals(updateUserInfoVo.getOldPassword())) {
                //将新密码保存到数据库
                String newPassword = updateUserInfoVo.getNewPassword();
                String newDataPass = AESUtils.encryptData(IV_STRING, newPassword);
                sysUser.setPassword(newDataPass);
                //进行更新
                userMapper.updateByPrimaryKeySelective(sysUser);
                return "修改密码成功";
            }
        }
        return "修改密码失败";
    }


    /**
     * 新增小组和小组-目标关联信息
     *
     * @param vo
     * @return
     */
    public String addGroup(SysGroupVo vo) {
        if (vo.getGroupId() == null) {
            String groupName = vo.getGroupName();
            if (StringUtils.isBlank(groupName)) {
                return "500,小组名称不可为空";
            }
            vo.setCreateTime(new Date());
            groupMapper.insertSelective(vo);
            Long groupId = vo.getGroupId();
            List<String> targetIds = vo.getTargetIds();

            if (targetIds != null) {
                GroupTarget groupTarget = new GroupTarget();
                for (String targetId : targetIds) {
                    groupTarget.setCreateTime(new Date());
                    groupTarget.setGroupId(groupId);
                    groupTarget.setTargetId(targetId);
                    groupTargetMapper.insertSelective(groupTarget);
                }
            }
        } else {
            updateGroup(vo);
        }
        return "200,操作成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String assignTarget(Long expertId, ArrayList<String> targetIds) {


        /**
         * 获得同一小组内,其他专家的id
         */

        List<UserGroup> userGroups = userGroupMapper.getOtherExpert(expertId);
        /**
         * 获得这些目标和子目标下的数据(图像，视频，资料  暂时只处理图像)
         */
        /**
         * 因为图像表中存储的targetxh指的是zbnm所以，根据xh获得编码
         */
        String xhsStr = StringUtils.join(targetIds, "','");
        List<NewTCodeTargetType> targets=targetMapper.getByXh("'"+xhsStr+"'");
        ArrayList<String> zbnmList = new ArrayList<>();
        if (targets!=null){
            for (NewTCodeTargetType newTCodeTargetType : targets) {
                zbnmList.add(newTCodeTargetType.getZbnm());
            }
        }



        String idsStr = StringUtils.join(zbnmList, "','");
        List<TImageInfo> imageInfos = imageInfoMapper.getDataByNm("'"+idsStr+"'");
        List<TVideoInfo> videoInfos = videoInfoMapper.getDataByNm("'"+idsStr+"'");
        /**
         * 其他专家对该目标下的数据审核意见全部设为通过
         */
        for (UserGroup userGroup : userGroups) {
            UserExamine userExamine = new UserExamine();
            userExamine.setUserId(userGroup.getUserId());
            userExamine.setGroupId(userGroup.getGroupId());
            userExamine.setExamineType(ExamineEnum.checked.getIndex());
            userExamine.setCreateTime(new Date());
            for (TImageInfo imageInfo : imageInfos) {
                userExamine.setMessageId(imageInfo.getId());
                userExamine.setTargetId(imageInfo.getTargetType());
                userExamine.setMediaType(MediaEnum.IMAGE.getIndex());
                userExamine.setCreateTime(new Date());
                examineMapper.insertSelective(userExamine);
            }
            for (TVideoInfo videoInfo : videoInfos) {
                userExamine.setMessageId(videoInfo.getId());
                userExamine.setTargetId(videoInfo.getTargetType());
                userExamine.setMediaType(MediaEnum.VIDEO.getIndex());
                examineMapper.insertSelective(userExamine);
            }
        }

        /**
         * 将为用户指定的目标进行存储
         */

        UserTarget userTarget = new UserTarget();

        userTargetMapper.deleteByUserId(expertId);
        for (String targetId : targetIds) {
            userTarget.setUserId(expertId);
            userTarget.setTargetId(targetId);
            userTarget.setCreateTime(new Date());
            userTargetMapper.insertSelective(userTarget);
        }
        return "200,操作成功";
    }

    public Object getAllGroup(Integer pageSize, Integer pageNo) {
        if (pageSize == null || pageSize == 0) {
            List<GroupAndTarget> all = groupMapper.getAll();
            for (GroupAndTarget groupAndTarget : all) {
                List<String> collect = groupAndTarget.getList().stream().map(GroupTarget::getTargetId).collect(Collectors.toList());
                groupAndTarget.setTargetTds(collect);
            }
            return all;
        }
        if (pageNo == null) {
            return "500,请传入pageNo";
        }
        PageHelper.startPage(pageNo, pageSize);
        List<GroupAndTarget> all = groupMapper.getAll();
        for (GroupAndTarget groupAndTarget : all) {
            List<String> collect = groupAndTarget.getList().stream().map(GroupTarget::getTargetId).collect(Collectors.toList());
            groupAndTarget.setTargetTds(collect);
        }
        return new PageInfo<GroupAndTarget>(all);

    }

    public Object getUsers(String searchName, Long groupId, Integer pageSize, Integer pageNo) {
        if (pageSize == null || pageSize == 0) {
            List<SysUserVo> users = userMapper.getUsers(searchName, groupId);
            for (SysUserVo user : users) {
                user.setPassword(backPassword(user.getPassword()));
            }
            return users;
        }
        if (pageNo == null) {
            return "500,请传入pageNo";
        }
        PageHelper.startPage(pageNo, pageSize);
        List<SysUserVo> users = userMapper.getUsers(searchName, groupId);
        for (SysUserVo user : users) {
            user.setPassword(backPassword(user.getPassword()));
        }
        return new PageInfo<SysUserVo>(users);
    }

    private String backPassword(String password) {
        return AESUtils.decryptData(password);
    }

    public Object updateGroup(SysGroupVo group) {

        group.setUpdateTime(new Date());
        /**
         * 更新小组和目标的关联关系
         */
        List<String> targetIds = group.getTargetIds();
        if (targetIds != null) {
            groupTargetMapper.deleteByGroupId(group.getGroupId());
            for (String targetId : targetIds) {
                GroupTarget groupTarget = new GroupTarget();
                groupTarget.setGroupId(group.getGroupId());
                groupTarget.setCreateTime(new Date());
                groupTarget.setTargetId(targetId);
                groupTargetMapper.insertSelective(groupTarget);
            }
        }
        return groupMapper.updateByPrimaryKeySelective(group);
    }

    public Object deleteGroup(Long groupId) {
        groupMapper.deleteByPrimaryKey(groupId);
        return "200,删除成功";
    }

    public Object updateUser(SysUserVo user) {
//        SysUser sysUser = userMapper.selectByPrimaryKey(user.getUserId());
//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(user.getUserId());
        String newPassword = AESUtils.encryptData(user.getPassword());
        user.setPassword(newPassword);
        user.setUpdateTime(new Date());
//        sysUser.setUserRole(user.getUserRole());
        userMapper.updateByPrimaryKeySelective(user);
        userGroupMapper.deleteByUserId(user.getUserId());
        if ("1".equals(user.getUserRole())|| "2".equals(user.getUserRole()))
        {
            return "200,编辑成功";
        }
        UserGroup userGroup = new UserGroup();
        userGroup.setUserId(user.getUserId());
        userGroup.setRoleType(user.getRoleType());
        userGroup.setGroupId(user.getGroupId());
        if ("3".equals(user.getRoleType())) {
            userGroup.setGroupId(0L);
        }
        userGroupMapper.insertSelective(userGroup);
        return "200,编辑成功";
    }

    public Object deleteUser(Long userId) {
        userMapper.deleteByPrimaryKey(userId);
        return "200,删除成功";
    }

    public void insertOrderStatus(String orderId, String status) {
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderName(orderId);
        orderStatus.setStatus(status);
        orderStatus.setCreateDate(new Date());
        orderStatusMapper.insertSelective(orderStatus);
    }
}
